package com.tangcan.blog.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.tangcan.blog.Entity.User;
import com.tangcan.blog.Mapper.UserMapper;
import com.tangcan.blog.Utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@EnableAutoConfiguration
public class UserService {

    private User ErrUser = new User(-1,"error","","","");
    @Autowired
    UserMapper userMapper;

    TokenUtils tokenUtils;

    //查询User是否存在
    public User CheckUserExist(String data)
    {
        //数据库里查询的User
        User ReqUser = JSON.parseObject(data,User.class);
        //前端POST的User
        User SqlUser =  userMapper.CheckUserExist(ReqUser);
        if (SqlUser != null)
        {

            return SqlUser;
        }
        else{
            return this.ErrUser;
        }
    }

    public JSONObject GetUserNameById(String data)
    {
        JSONObject json = JSON.parseObject(data, Feature.OrderedField);
        JSONObject resJson = new JSONObject();
        int id = json.getInteger("id");
        User user = userMapper.FindUserById(id);
        resJson.put("userName",user.getUserName());
        return resJson;

    }

    public JSONObject UserLogin(String data )
    {

        User ReqUser = JSON.parseObject(data,User.class);
        User SqlUser =  userMapper.CheckUserExist(ReqUser);
        if (SqlUser !=null)
        {
            if (SqlUser.getPassWord().equals(ReqUser.getPassWord()) && SqlUser.getAuthority().equals(ReqUser.getAuthority()))
            {
                    //登陆成功 生成token
                int Id = SqlUser.getId();
                String UserName = SqlUser.getUserName();
                String PassWord = SqlUser.getPassWord();
                String Authority = SqlUser.getAuthority();
                String token = tokenUtils.token(Id,UserName,PassWord,Authority);
                System.out.println(token);
                JSONObject resJson = new JSONObject(true);
                resJson.put("token",token);
                resJson.put("code","ok");

                return resJson;

            }
            else {
                JSONObject resJson = new JSONObject(true);
                resJson.put("info","密码/用户名/权限错误");
                resJson.put("code","err");
                return resJson;
            }
        }
        else {
            JSONObject resJson = new JSONObject(true);
            resJson.put("info","用户不存在");
            resJson.put("code","err");
            return resJson;

        }


    }

    public JSONObject GetAll(String data)
    {
        JSONObject json = JSON.parseObject(data, Feature.OrderedField);
        String token = json.get("token").toString();
        if (tokenUtils.verify(token))
        {

            Map tokenInfo = tokenUtils.getTokenInfo(token);
            String authority = tokenInfo.get("authority").toString().replace("\"","");
            if (authority.equals("admin"))
            {
                JSONObject resJson = new JSONObject(true);
                resJson.put("UserList",userMapper.GetAll());
                resJson.put("code","ok");
                return resJson;
            }
            else
            {
                JSONObject resJson = new JSONObject(true);
                resJson.put("code","err");
                resJson.put("info","不是管理员");
                return resJson;
            }
        }
        else
        {
            System.out.println("token验证不成功");
            JSONObject resJson = new JSONObject(true);
            resJson.put("code","err");
            resJson.put("info","重新登陆");
            return resJson;
        }

    }
    public JSONObject RefreshToken(String data)
    {
        JSONObject json = JSON.parseObject(data, Feature.OrderedField);
        String OldToken = json.getString("oldToken");
        JSONObject resJson = new JSONObject(true);

        if (tokenUtils.verify(OldToken))
        {
            Map tokenInfo = tokenUtils.getTokenInfo(OldToken);
            int Id = Integer.parseInt(tokenInfo.get("id").toString().replace("\"",""));
            String authority = tokenInfo.get("authority").toString().replace("\"","");
            String username = tokenInfo.get("username").toString().replace("\"","");
            String password = tokenInfo.get("authority").toString().replace("\"","");
            String NewToken = tokenUtils.token(Id,username,password,authority);
            resJson.put("code","ok");
            resJson.put("newToken",NewToken);
        }
        else
        {
            resJson.put("code","err");
            resJson.put("info","OldToken已经过期不能刷新");

        }
        return resJson;



    }
    public  JSONObject AddUser(String data)
    {
        JSONObject json = JSON.parseObject(data, Feature.OrderedField);
        User REuser = JSONObject.parseObject(json.get("newUser").toString(), User.class);
        String token = json.get("token").toString();
        JSONObject resJson = new JSONObject(true);
        if (tokenUtils.verify(token))
        {
            Map tokenInfo = tokenUtils.getTokenInfo(token);
            String authority = tokenInfo.get("authority").toString().replace("\"","");
            if (authority.equals("admin"))
            {
                if (REuser.getUserName().isEmpty() || REuser.getAuthority().isEmpty() || REuser.getPassWord().isEmpty() )
                {
                    resJson.put("info","存在空值");
                    resJson.put("code","err");
                }
                else
                {
                    userMapper.AddUser(REuser);
                    resJson.put("info",REuser);
                    resJson.put("code","ok");
                }
            }
            else
            {
                resJson.put("info","不是管理员");
                resJson.put("code","err");
            }

        }
        else {
            resJson.put("info","token不正确");
            resJson.put("code","err");
        }
        return resJson;
    }

    public  JSONObject UpdateUser(String data,int type)
    {
        JSONObject json = JSON.parseObject(data, Feature.OrderedField);
        String token = json.get("token").toString();
        JSONObject resJson = new JSONObject(true);
        if (tokenUtils.verify(token))
        {

            Map tokenInfo = tokenUtils.getTokenInfo(token);
            String authority = tokenInfo.get("authority").toString().replace("\"","");
            if (authority.equals("admin"))
            {
                //是管理员
                Integer id = json.getInteger("id");
               if (type == 1) {
                   String username = json.getString("UserName");
                   if (!username.isEmpty())
                   {
                       userMapper.UpdateUserNameById(id,username);
                       resJson.put("info","成功改名");
                       resJson.put("code","ok");
                   }else
                   {
                       resJson.put("info","username Not Allow null");
                       resJson.put("code","err");
                       return resJson;
                   }

               }
               if (type==2)
               {
                   String passwd = json.getString("PassWord");
                   if (!passwd.isEmpty())
                   {
                       userMapper.UpdatePasswdById(id,passwd);
                       resJson.put("info","成功改密码");
                       resJson.put("code","ok");
                   }else
                   {
                       resJson.put("info","PassWord Not Allow null");
                       resJson.put("code","err");
                       return resJson;
                   }
               }
               if(type == 3)
               {

                   String usericon = json.getString("UserIcon");
                   userMapper.UpdateIconById(id,usericon);
                   resJson.put("info","成功头像");
                   resJson.put("code","ok");
               }
            }
            else
            {
                //不是管理员
                Integer id =  (int) tokenInfo.get("Id");
                if (type == 1) {
                    String username = json.getString("UserName");
                    if (!username.isEmpty())
                    {
                        userMapper.UpdateUserNameById(id,username);
                        resJson.put("info","成功改名");
                        resJson.put("code","ok");
                    }else
                    {
                        resJson.put("info","username Not Allow null");
                        resJson.put("code","err");
                        return resJson;
                    }

                }
                if (type==2)
                {
                    String passwd = json.getString("PassWord");
                    if (!passwd.isEmpty())
                    {
                        userMapper.UpdatePasswdById(id,passwd);
                        resJson.put("info","成功改密码");
                        resJson.put("code","ok");
                    }else
                    {
                        resJson.put("info","PassWord Not Allow null");
                        resJson.put("code","err");
                        return resJson;
                    }
                }
                if(type == 3)
                {

                    String usericon = json.getString("UserIcon");
                    userMapper.UpdateIconById(id,usericon);
                    resJson.put("info","成功头像");
                    resJson.put("code","ok");
                }



            }

        }
        else {
            resJson.put("info","token不正确");
            resJson.put("code","err");
        }
        return resJson;
    }
    public JSONObject SearchUser(String data)
    {
        System.out.println("原始:"+data);
        JSONObject json = JSON.parseObject(data, Feature.OrderedField);
        String token = json.get("token").toString();
        String Condition = json.getString("Condition").toString();
        JSONObject resJson = new JSONObject();
        if (tokenUtils.verify(token))
        {
            Map tokenInfo = tokenUtils.getTokenInfo(token);
            String authority = tokenInfo.get("authority").toString().replace("\"","");
            if (authority.equals("admin"))
            {
                List<User> res = userMapper.SearchUser(Condition);
//                System.out.println(res);
                resJson.put("UserList",res);
                resJson.put("code","ok");

            }
            else
            {
                resJson.put("info","不是管理员");
                resJson.put("code","err");
            }
        }
        else
        {
            resJson.put("info","token不正确");
            resJson.put("code","err");
        }
        return resJson;
    }
    public JSONObject FindByUserName(String data)
    {
        JSONObject json = JSON.parseObject(data, Feature.OrderedField);
        String UserName = json.getString("name");
        JSONObject resJson = new JSONObject();
        resJson.put("res",userMapper.FindByUserName(UserName));

        return resJson;

    }
    public JSONObject GetAdminNameMap()
    {
        JSONObject resJson = new JSONObject();
        List<User> userList = userMapper.GetAdminName();

        for (User user:userList)
        {
            resJson.put(user.getId()+"",user.getUserName());
        }
        return resJson;
    }

}
